/**
 * jQuery upload v1.0
 *
 * @author rayinhz
 */
(function ($) {
    var noop = function () {
        return true;
    };

    $.uploadDefault = {
        url: '',
        domId: '',
        dataType: 'json',
        params: {},
        onSend: noop,
        onComplate: noop,
        onError: noop
    };

    $.uploadOption = {};

    $.upload = function (options) {
        $.uploadOption = $.extend(jQuery.uploadDefault, options);
        if ($.uploadOption.url == '') {
            return;
        }

        var canSend = $.uploadOption.onSend();
        if (!canSend) {
            return;
        }

        //	添加iframe和form
        var frameName = 'toolkit_upload_frame';
        var formName = 'toolkit_upload_form';
        var iframe = $('<iframe id="' + frameName + '" name="' + frameName + '" onload="$.uploadCallback();" style="position:absolute;top:-9999px"></iframe>');
        var form = $('<form name="' + formName + '" method="post" style="display:none;" enctype="multipart/form-data"></form>');
        form.attr("target", frameName).attr('action', $.uploadOption.url);
//		iframe.appendTo("body");
        $("body").append(iframe);
        iframe.append(form);

        //	处理上传的额外参数
        var formHtml = "";
        for (var key in $.uploadOption.params) {
            formHtml += '<input type="hidden" name="' + key + '" value="' + $.uploadOption.params[key] + '" />';
        }
        form.append(formHtml);

        //	处理file input控件
        var oldElement = $('#' + $.uploadOption.domId);
        var newElement = $("<input id='toolkit_upload_file_clone' type='hidden' />");
        newElement.insertAfter(oldElement);
		form.append(oldElement);

        try {
            //	开始提交上传
            form.submit();
        } catch (e) {
            $.uploadOption.onError(e);
        }
    };

    // iframe 在提交完成之后
    $.uploadCallback = function () {
        var iframe = $("#toolkit_upload_frame");
//		处理file input控件
        var oldElement = $('#' + $.uploadOption.domId);
        var newElement = $('#toolkit_upload_file_clone');
        oldElement.insertAfter(newElement);
        newElement.remove();

        //	处理真正的业务流程
        var xml = {};
        var io = iframe[0];
        if (io.contentWindow) {
            xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerText : null;
        } else if (io.contentDocument) {
            xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerText : null;
        }
        var data = xml.responseText;
        if (data == "") {
            return;
        }
        if (data.substr(0, 1) != "{") {
            data = {isTrue: false, message: data};
        } else {
            eval("data = " + data);
        }
        $.uploadOption.onComplate(data);
        window.setTimeout(function () {
            iframe.remove();
        }, 5000);
    }
})(jQuery);





